package org.stvd.repository.oauth.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.stvd.common.utils.StringsUtil;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.oauth.OauthAccessToken;
import org.stvd.repository.base.impl.BaseDaoImpl;
import org.stvd.repository.oauth.OauthAccessTokenDao;

/**
 * 授权Token Repository实现类
 * @author houzx
 */
@Repository("OauthAccessTokenDao")
public class OauthAccessTokenDaoImpl extends BaseDaoImpl<OauthAccessToken> 
    implements OauthAccessTokenDao{

    @Override
    public QueryResult<Map<String, Object>> queryAccessTokenResult(int start, int limit, String user_name, String client_id, String grant_type) {
        String sql = "SELECT T1.token_id, T1.token, T1.authentication_id, T2.uname, T1.client_id, T1.authentication, T1.refresh_token,"
            + "T1.create_time from oauth_access_token T1 LEFT OUTER JOIN users T2 on T1.user_name = T2.user_id WHERE 1 = 1 ";
        Map<String, Object> params = new HashMap<>();
        if (StringsUtil.isNotEmpty(grant_type)) {
            if("password".equals(grant_type)) {
                sql += " AND T2.uname like :userName ";
                params.put("userName", "%"+user_name+"%");
            } else {
                sql += " AND T2.uname is null";
            }
        }
        if(!StringUtil.isEmpty(client_id)) {
            sql += " AND T1.client_id = :clientId";
            params.put("clientId", client_id);
        }
        sql    += " ORDER BY T1.create_time DESC";
        System.out.println(sql);
        return this.getQueryResultBySQLToMap(start, limit, sql, params);
    }
    
    @Override
    public List<Map<String, Object>> listAccessToken(String userName) {
        String sql = "SELECT T1.token_id, T1.user_name, T1.client_id, T1.refresh_token"
            + " FROM oauth_access_token T1"
            + " WHERE T1.user_name = :userName";
        Map<String, Object> params = new HashMap<>();
        params.put("userName", userName);
        return findBySQLToMap(sql, params);
    }

}
